package common.kit;

import com.jfinal.kit.StrKit;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.model.FetchRet;
import com.qiniu.util.Auth;

public class QiniuKit {
	
	static Auth auth = Auth.create( PropKits.getAccessKey() , PropKits.getSecretKey() );
	
	public static String fetch(String url) {
		if (StrKit.isBlank(url) || url.indexOf(PropKits.getDomain()) > -1 ) {
			return url ;
		}
		//构造一个带指定Zone对象的配置类
		Configuration cfg = new Configuration(Zone.zone0());
		Auth auth = Auth.create(PropKits.getAccessKey(), PropKits.getSecretKey());
		BucketManager bucketManager = new BucketManager(auth, cfg);
		//抓取网络资源到空间
		try {
		    FetchRet fetchRet = bucketManager.fetch(url, PropKits.getBucket() );
		    if (null != fetchRet) {
				return PropKits.getDomain()  + fetchRet.key ;
			}
		} catch (QiniuException ex) {
		    System.err.println(ex.response.toString());
		}
		return url ;
	}
	
	public static String getUpToken() {
		return auth.uploadToken(PropKits.getBucket());
	}
	
}
